package com.hjy.servlet;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;

import com.cloopen.rest.sdk.CCPRestSmsSDK;

import redis.clients.jedis.Jedis;
import com.hjy.utils.JedisUtil;
import com.hjy.utils.SmsUtil;

public class SmsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String phone = request.getParameter("phone");
		
		// 模板1的形式为：【云通讯】您使用的是云通讯短信模板，您的验证码是{1}，请于{2}分钟内正确输入。
	    String templateId= "1";
	    
	    //随机生成4位数字作为验证码
	    String code = RandomStringUtils.randomNumeric(4);
	    //过期时间,单位分钟
	    String expire = "5";
		
		String[] datas = {code, expire};
		
		//发送短信
		boolean result = SmsUtil.sendSms(phone, "1", datas);
		
		if (!result) {
			response.getWriter().print("0");
		}
		
		//将验证码存储到redis
		Jedis jedis = JedisUtil.getJedis();
		jedis.setex("register::"+phone, Integer.parseInt(expire)*60, code);
		JedisUtil.closeJedis(jedis);
		
		response.getWriter().print("1");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
